import { defineStore } from "pinia";
import { login, logout, getSubject } from "@/api/login";
import { removeToken, setToken } from "@/utils/auth";
import { ElMessage } from "element-plus";

export const useUserStore = defineStore("user", {
  state: () => {
    return {
      userInfo: {} as userInfo,
    };
  },
  actions: {
    userLogin(data: LoginData) {
      login(data).then((res: apiServerResponseType) => {
        if (res.code == 200) {
          setToken(res.result.token);
          this.userInfo.realName = res.result.realName;
          this.userInfo.userId = res.result.userId;
          this.userInfo.username = res.result.username;
          window.location.href = "/";
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    getUserInfo() {
      getSubject().then((res: apiServerResponseType) => {
        if (res.code == 200) {
          this.userInfo.realName = res.result.realName;
          this.userInfo.userId = res.result.userId;
          this.userInfo.username = res.result.username;
          this.userInfo.deptName = res.result.deptName;
          this.userInfo.mobile = res.result.mobile;
          this.userInfo.email = res.result.email;
          this.userInfo.gender = res.result.gender;
          this.userInfo.headUrl = res.result.headUrl;
        }
      });
    },

    // 退出登录
    userLogout() {
      logout().then(() => {
        removeToken();
        window.location.href = "/login";
      });
    },
  },
});
